<template>
	<view id="account_book_container">
		<uni-swipe-action>
			<uni-swipe-action-item
				v-for="(item, index) of accountBookData"
			 	:key="index"
				:right-options="optionsRight" 
				:left-options="optionsLeft" 
				@click="beforeHandleOfDelete($event, item)" 
				:class="{'not-first_book': index != 0}"
				>
				<!-- 账本列表 -->
				<view class="account_books" @click="intoAccountBookDetail(item)">
					<view class="account_books_left">
						<view class="account_books_left_name">
							{{ item.name }}
							<span class="defaultTag" v-if="item.isDefault == 1">默认</span>
						</view>
						<view class="account_books_left_number"> 
							共 {{ item.billData.totalBillNum }} 笔账单
						</view>
						<view class="account_books_left_IE">
							收￥{{ item.billData.income }} / 支 ￥{{ item.billData.expenditure }}
						</view>
					</view>
					<view class="account_books_right">
						<view class="account_books_right_text">
							结余
						</view>
						<view class="account_books_right_value">
							{{ item.billData.balance }}
						</view>
					</view>
				</view>
				<view style="height: 11px;"></view>
			</uni-swipe-action-item>
		</uni-swipe-action>
		<!-- 底部新增按钮 -->
		<view class="add_btn">
			<button 
				type="default" 
				style="background-color: #efa31f; color: #fff;"
				@click="addBookHandle"
				>
				新增
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';

// 存储传入的用户openId
let OpenId = '';
// 账本数据
let accountBookData = ref([]);

// 滑块参数
let optionsRight = [
	{
		text: '删除',
		style: {
			backgroundColor: '#dd524d'
		}
	}
];
let optionsLeft = [
	{
		text: '设默认',
		style: {
			backgroundColor: '#42a2dd'
		}
	}
];

onLoad((option) => {
	OpenId = option.openId;
});

onMounted(() => {
	getUserAllAccountBook();
});

onShow(()=>{
	refreshData();
})

// 删除的前置处理
function beforeHandleOfDelete(e, item){
	let msg = "";
	if(e.content.text == "设默认"){
		msg = "确定设置默认？"
	}else{
		msg = "删除操作不可逆，是否继续？"
	}
	
	uni.showModal({
		title: '提示',
		content: msg ,
		success: function (res) {
			if (res.confirm) {
				bookOptionHandle(e, item)
			} else if (res.cancel) {
				uni.$showT('取消操作');
			}
		}
	});
}

// 左右滑动功能处理器
function bookOptionHandle(e, item){	
	// 区分处理设为默认或是删除账本
	if(e.content.text == "设默认"){
		setDefaultHandle(item);
		return 1;
	}
	
	// 删除逻辑，首先判断当前的账本数量，如果为1则不允许删除
	if(accountBookData.value.length <= 1){
		uni.showToast({
			title:"必须保留一个账本",
			icon:"none"
		})
		return;
	}
	
	// 允许删除，执行删除
	execDelete(item);
}

// 进入到账本详细页面
function intoAccountBookDetail(accountBook){
	// 序列化后传递
	let bookDataParam = JSON.stringify(accountBook);
	uni.navigateTo({
		url:`/subPkg1/book_detail/book_detail?bookData=${bookDataParam}`
	})
}

// 获取用户所有的账本数据
async function getUserAllAccountBook() {
	// 重本地存储中获取
	accountBookData.value = uni.getStorageSync("accountBookData"); // 存储账本数据
}

// 将账本设置默认账本
async function setDefaultHandle(accountBook){
	if(accountBook.isDefault == 1){
		uni.$showT("此账本已是默认，无需设置");
		return 1;
	}
	
	// 执行设置操作
	const res = await uni.$http.put(`/accountBooks/setDefault/${accountBook.id}`);
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	afterHandle();
}

// 删除账本
async function execDelete(book){
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	
	// 前端需要做：如果删除的账本为“当前选择”的账本，需要将当前选择的账本改为其他账本，采取按顺序array[0]选择。
	// 判断此账本是否为正在选择的账本
	if(book.name == uni.getStorageSync("selectedBook")){
		console.log("删除账本为当前选择的账本");
		// 获取非删除的账本，按顺序设置为“选择的账本”
		let notDeleteBooks = accountBookData.value.filter((item)=>{
			return  item.id != book.id
		});
		
		console.log("开始自动选择账本，候选账本：", notDeleteBooks);
		// 执行删除
		const res = await uni.$http.delete(`/accountBooks/${userInfo.id}/${book.id}`);
		// 删除成功，取候选账本中的第一个账本为 已选择的账本。
		uni.setStorageSync("selectedBook", notDeleteBooks[0].name);
		afterHandle()
	}else{
		const res = await uni.$http.delete(`/accountBooks/${userInfo.id}/${book.id}`);
		afterHandle();
	}
	
}

// 后置处理器
async function afterHandle(){
	// 删除成功后刷新数据
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	const res = await uni.$http.get(`/accountBooks/getAllByOpenId?openId=${userInfo.openid}`);
	// TODO通过默认账本字段排序
	
	accountBookData.value = res.data.data;
	uni.setStorageSync("accountBookData", accountBookData.value); 
}

// 新增处理器
function addBookHandle(){
	uni.navigateTo({
		url:"/subPkg1/add_book/add_book"
	}) 
}

// 刷新数据 保证数据实时性
function refreshData(){
	if(uni.getStorageSync("accountBookData") == ""){
		uni.$showT("暂无账本");
		return 0;
	}
	accountBookData.value = uni.getStorageSync("accountBookData");
	
	getBiilDataOfAccount(accountBookData.value)
}

// 获取账本的账单数据
async function getBiilDataOfAccount(accounts){
	// 构造请求参数
	let accountIds = [];
	for (let account of accounts) {
		accountIds.push(account.id);
	}
	
	const res = await uni.$http.post("/accountBooks/getBillStatisticsOfBook", accountIds);
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	// 遍历获得的账本账单统计数据，动态添加字段
	for (let item of accountBookData.value) {
		let tempId = item.id + "";
		
		let billDTemp = res.data.data[tempId];
		
		for (let key in billDTemp) {
			if (key !== "bookId" && key !== "totalBillNum") {
			    billDTemp[key] = billDTemp[key].toFixed(2);
			}
		}
		
		item.billData = billDTemp;
	}
	
}

</script>

<style lang="scss" scoped>
	
.account_books{
	width: 97%;
	background-color: #fff;
	margin: 0 auto;
	border-radius: 15rpx;
	display: flex;
	box-sizing: border-box;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	font-size: 14px;
	color: #6a6a6a;
	// font-weight: 600;
	background: linear-gradient(to bottom right, #fffdd5, #ffce7e);
}

.not-first_book{
	margin-top: 11px;
}

.account_books_left_name{
	font-size: 17px;
	color: #000;
	font-weight: 600;
}

.account_books_left_number{
	padding: 10rpx 0px;
}

.account_books_left_IE{
	font-size: 12px;
	margin-top: 20rpx;
	color: #242424;
}

.account_books_right{
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.account_books_right_value{
	font-size: 16px;
	color: #000;
	font-weight: 600;
}

.defaultTag{
	background: none;
	font-size: 13px;
	// font-weight: 600;
	border: solid #989898 1px;
	color: #989898;
	padding: 4rpx 8rpx;
	border-radius: 6px;
}

.add_btn{
	position: fixed;
	bottom: 0px;
	width: 100vw;
}

.add_btn button{
	width: 97%;
}
</style>